package com.coocaa.ops.common.tool.math;

import lombok.experimental.UtilityClass;

import java.text.DecimalFormat;

/**
 * @author bjh
 * @description
 * @date 2021/6/25 15:06
 */
@UtilityClass
public class RoundUtil {

    public static String round(String numStr, int nd) {
        String pattern = getPattern(nd);
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
        String finalSore = decimalFormat.format(Float.valueOf(numStr));
        return finalSore;
    }

    public static String round(float num, int nd) {
        String pattern = getPattern(nd);
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
        String finalSore = decimalFormat.format(num);
        return finalSore;
    }

    public static float roundFloat(float num, int nd) {
        String pattern = getPattern(nd);
        DecimalFormat decimalFormat = new DecimalFormat(pattern);
        String finalSore = decimalFormat.format(num);
        return Float.valueOf(finalSore);
    }

    private static String getPattern(int nd) {
        StringBuilder info = new StringBuilder();
        info.append(".");
        for (int i = 0; i < nd; i++) {
            info.append("0");
        }
        return info.toString();
    }

    public static void main(String[] args) {

//        System.out.println(round(1.24f, 1));
//        System.out.println(round(1.28f, 1));
//        System.out.println(round(9, 1));
//        System.out.println(round("5", 1));
//        System.out.println(round("1.28", 1));
    }
}
